<?php
App::uses('AdminAppController', 'Admin.Controller');
/**
 * AdminProductsController
 *
 * @property Product $Product
 */
class AdminProductsController extends AdminAppController {

	public $uses = array('Product', 'ProductDetail', 'ProductCategory', 'ProductBrand');

    public function index() {
	    $conditions = array();
        $productsTableURL = array('controller' => 'admin_products', 'action' => 'index');

        //join get query & named params
        $params = array_merge($this->request->params['named']);
        foreach($this->request->query as $key => $value) $params[$key] = $value;

        foreach($params as $key => $value) {
            $split = explode('-', $key);
            $modelName = (sizeof($split) > 1) ? $split[0] : 'Product';
            $property = (sizeof($split) > 1) ? $split[1] : $key;
            if($modelName == 'Product' || !empty($this->Product->belongsTo[$modelName])) {
                $this->loadModel($modelName);
                $modelObj = new $modelName();
                if(!empty($modelObj)) {
                    $columnType = $modelObj->getColumnType($property);
                    if(!empty($columnType)){
                        //add it to url
                        $productsTableURL[$key] = $value;
                        //add it to conditions
                        switch($columnType)
                        {
                            case 'string':
                                $conditions[$modelName . '.' . $property . ' LIKE'] = '%'.$value.'%';
                                break;
                            default:
                                $conditions[$modelName . '.' . $property] = $value;
                                break;
                        }
                    }
                }
            }

        }
        
        $brand = $this->request->data('brand_id');
        if($brand) {
            $this->request->data['brand_id'] = $brand;
            $this->loadModel('ProductCategory');
            $this->ProductCategory->recursive = -1;
            $listCate = $this->ProductCategory->find('all', array('conditions' => array('product_brand_id' => $brand)));
            $list = array();
            foreach($listCate as $cate) {
                $list[] = $cate['ProductCategory']['id'];
            }
            $conditions = array('product_category_id' => $list);
        }
		$this->Product->recursive = 2;
		$this->paginate = array('conditions' => $conditions, 'limit' => 30);
        $this->set('products', $this->Paginator->paginate('Product'));
		$this->set('productsTableURL', $productsTableURL);
        $this->set('productsTableModelAlias', 'Product');
        
        $this->loadModel('ProductBrand');
        $productBrands = $this->ProductBrand->find('all', array('order' => 'ProductBrand.'.$this->ProductBrand->displayField));
		$productBrandsSelect = Hash::combine($productBrands, '{n}.ProductBrand.id', '{n}.ProductBrand.toString');
        $this->set('productBrandsSelect', $productBrandsSelect); 
		
        //render as local table if it is an ajax request
        if($this->request->is('ajax'))
        {
            $this->render('table');
        }
	}
    
	public function add() {
		if ($this->request->is('post')) {
			$this->Product->create();
			$data = $this->request->data;
			if ($this->Product->save($data['Product'])) {
				if($this->saveProductElement($this->Product->id, $data['ProductDetail'])){
					$this->Session->setFlash(__('The product has been saved'), 'default', array(), 'good');
					if(!empty($this->request->query['redirect'])) {
						$this->redirect($this->redirectUrl);
					} else {
						$this->redirect(array('action' => 'index'));
					}
				} else {
					$this->Session->setFlash(__('The product element could not be saved. Please, try again.'), 'default', array(), 'bad');
				}
			} else {
				$this->Session->setFlash(__('The product could not be saved. Please, try again.'), 'default', array(), 'bad');
			}
            
            $productDetail = array();
            foreach($data['ProductDetail']['description'] as $key=>$description) {
                $productDetail[$key]['description'] = $description;
                $productDetail[$key]['code'] = $data['ProductDetail']['code'][$key];
                $productDetail[$key]['cocoa_solids'] = $data['ProductDetail']['cocoa_solids'][$key];
                $productDetail[$key]['packaging'] = $data['ProductDetail']['packaging'][$key];
                
                $productDetail[$key]['description_en'] = $description;
                $productDetail[$key]['code_en'] = $data['ProductDetail']['code_en'][$key];
                $productDetail[$key]['cocoa_solids_en'] = $data['ProductDetail']['cocoa_solids_en'][$key];
                $productDetail[$key]['packaging_en'] = $data['ProductDetail']['packaging_en'][$key];
            }
            $this->set('productDetail', $productDetail );
		} else {
            //add the named params as data
            foreach($this->request->params['named'] as $param => $value) {
                $columnType = $this->Product->getColumnType($param);
                if(!empty($columnType)) {
                    if(empty($this->request->data['Product'])) $this->request->data['Product'] = array();
                    $this->request->data['Product'][$param] = $value;
                    //is this a reference to a related object?
                    foreach ($this->Product->belongsTo as $relationName => $relationInfo) {
                    	if($relationInfo['foreignKey'] == $param) {
                    		$relatedRecord = $this->Product->$relationInfo['className']->find('first', array('conditions' => array($relationInfo['className'] . '.id' => $value), 'recursive' => 0));
                    		$this->set(Inflector::variable($relationInfo['className']), $relatedRecord);
                    	}
                    }
                }
            }
        }
		$productCategories = $this->Product->ProductCategory->find('all', array('order' => 'ProductCategory.'.$this->Product->ProductCategory->displayField));
		$productCategoriesSelect = Hash::combine($productCategories, '{n}.ProductCategory.id', '{n}.ProductCategory.toString');
        
        $productBrands = $this->ProductBrand->find('all', array('order' => 'ProductBrand.'.$this->ProductBrand->displayField));
		$productBrandsSelect = Hash::combine($productBrands, '{n}.ProductBrand.id', '{n}.ProductBrand.toString');
        
		$this->set(compact('productCategories', 'productCategoriesSelect', 'productBrandsSelect'));
	}
	
	public function edit($id = null) {
		$this->Product->id = $id;
		if (!$this->Product->exists()) {
			throw new NotFoundException(__('Invalid product'));
		}
		if ($this->request->is('post') || $this->request->is('put')) {
			$data = $this->request->data;
			if ($this->Product->save($data['Product'])) {
				if($this->saveProductElement($this->Product->id, $data['ProductDetail'])){
					$this->Session->setFlash(__('The product has been saved'), 'default', array(), 'good');
					$this->redirect($this->redirectUrl);
				} else {
					$this->Session->setFlash(__('The product element could not be saved. Please, try again.'), 'default', array(), 'bad');
				}
			} else {
				$this->Session->setFlash(__('The product could not be saved. Please, try again.'), 'default', array(), 'bad');
			}
		} else {
            $product = $this->Product->read(null, $id);
            $product['Product']['brand_id'] = $product['ProductCategory']['product_brand_id'];
			$this->request->data = $product;
		}
        
        $brandId = $this->request->data['Product']['brand_id'];
		$productCategories = $this->Product->ProductCategory->find('all', array('conditions'=>array('ProductCategory.product_brand_id' => $brandId), 'order' => 'ProductCategory.'.$this->Product->ProductCategory->displayField));
		$productCategoriesSelect = Hash::combine($productCategories, '{n}.ProductCategory.id', '{n}.ProductCategory.toString');
		
        $productBrands = $this->ProductBrand->find('all', array('order' => 'ProductBrand.'.$this->ProductBrand->displayField));
		$productBrandsSelect = Hash::combine($productBrands, '{n}.ProductBrand.id', '{n}.ProductBrand.toString');
        
		$this->ProductDetail->recursive = -1;
		$productDetail = $this->ProductDetail->find('all', array('conditions' => array('ProductDetail.product_id' => $id)));
		
		$this->set(compact('productCategories', 'productCategoriesSelect', 'productDetail', 'productBrandsSelect'));
	}
	
	public function delete($id = null) {
		if (!$this->request->is('post')) {
			throw new MethodNotAllowedException();
		}
		$this->Product->id = $id;
		if (!$this->Product->exists()) {
			throw new NotFoundException(__('Invalid product'));
		}
		if ($this->Product->delete()) {
			$this->Session->setFlash(__('Product deleted'), 'default', array(), 'good');
            $this->redirect($this->redirectUrl);
		}
		$this->Session->setFlash(__('Product was not deleted'), 'default', array(), 'bad');
		$this->redirect(array('action' => 'index'));
	}
	
	public function saveProductElement($productId, $data) {

		$productDetail = array();
		foreach($data['product_detail_id'] as $key=>$value) {
			$productDetail[$key]['product_id'] = $productId;
			
			if(!empty($data['product_detail_id'][$key])) {
				$productDetail[$key]['product_detail_id'] = $value;
			}
			
			if(!empty($data['description'][$key])) {
				$productDetail[$key]['description'] = $data['description'][$key];
				$productDetail[$key]['description_en'] = $data['description_en'][$key];
			}
			
			if(!empty($data['code'][$key])) {
				$productDetail[$key]['code'] = $data['code'][$key];
				$productDetail[$key]['code_en'] = $data['code_en'][$key];
			}
			
			if(!empty($data['cocoa_solids'][$key])) {
				$productDetail[$key]['cocoa_solids'] = $data['cocoa_solids'][$key];
				$productDetail[$key]['cocoa_solids_en'] = $data['cocoa_solids_en'][$key];
			}
			
			if(!empty($data['packaging'][$key])) {
				$productDetail[$key]['packaging'] = $data['packaging'][$key];
				$productDetail[$key]['packaging_en'] = $data['packaging_en'][$key];
			}
		}

		if($this->ProductDetail->saveAll($productDetail)) {
			return true;
		} 
		
		return false;
	}
	
	public function deleteProductEmelent() {
        $this->autoRender = false;
        if (!$this->request->is('post')) {
			$this->response->body(0);
            return;
		}
        $this->ProductDetail->id = $this->request->data('id');
		if (!$this->ProductDetail->exists()) {
			$this->response->body(0);
            return;
		}
		if ($this->ProductDetail->delete()) {
			$this->response->body(1);
            return;
		}
		
        $this->response->body(0);
        return;
	}	
    
    public function changeBrand()
    {
        $brandId = $this->request->data('brandId');
        $productCategories = $this->ProductCategory->find('all', array('conditions' => array('ProductCategory.product_brand_id' => $brandId), 'order' => 'ProductCategory.'.$this->ProductCategory->displayField));
        $productCategoriesSelect = Hash::combine($productCategories, '{n}.ProductCategory.id', '{n}.ProductCategory.toString');
        
        $this->set('productCategoriesSelect', $productCategoriesSelect);
        $this->render('category_list');
    }
}
